<template>
  <el-container>
    <aside-layout></aside-layout>
    <el-main>
      <div class="header">
        <h2>床位全景</h2>
      </div>

      <!-- 统计信息模块 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="8">
          <el-card shadow="hover" class="statistics-card">
            <div slot="header" class="clearfix">
              <span>统计信息</span>
            </div>
            <div class="statistics">
              <div class="stat-item">
                <i class="el-icon-s-home stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">总床位数</p>
                  <p class="stat-value">{{ bedList.length }}</p>
                </div>
              </div>
              <div class="stat-item">
                <i class="el-icon-user-solid stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">已入住</p>
                  <p class="stat-value">{{ occupiedBeds }}</p>
                </div>
              </div>
              <div class="stat-item">
                <i class="el-icon-s-check stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">空闲床位</p>
                  <p class="stat-value">{{ availableBeds }}</p>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 床位分布图 -->
        <el-col :span="16">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>床位分布图</span>
            </div>
            <div ref="bedChart" style="height: 300px;"></div> <!-- 使用 ref 获取容器 -->
          </el-card>
        </el-col>
      </el-row>

      <!-- 床位使用率图表 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>已入住床位</span>
            </div>
            <div ref="occupiedChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>空闲床位</span>
            </div>
            <div ref="availableChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 通知模块 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>通知</span>
              <el-button type="primary" icon="el-icon-plus" @click="handleAddNotification" style="float: right;">新增通知</el-button>
            </div>
            <ul class="notification-list">
              <li v-for="(notification, index) in notifications" :key="index">
                {{ notification.content }}
                <el-button type="text" @click="handleEditNotification(notification)">编辑</el-button>
                <el-button type="text" @click="handleDeleteNotification(notification)" class="delete-btn">删除</el-button>
              </li>
            </ul>
          </el-card>
        </el-col>
      </el-row>

      <!-- 床位信息表格 -->
      <el-button type="primary" icon="el-icon-plus" @click="handleAddBed" style="margin-bottom: 20px;">新增床位</el-button>
      <el-table :data="bedList" style="width: 100%" border stripe>
        <el-table-column prop="roomNumber" label="房间号" width="100"></el-table-column>
        <el-table-column prop="bedNumber" label="床位号" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '空闲' ? 'success' : 'info'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="elderlyName" label="入住老人" width="150"></el-table-column>
        <el-table-column prop="admissionDate" label="入住日期" width="150"></el-table-column>
        <el-table-column prop="careLevel" label="护理等级" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.careLevel === '高' ? 'danger' : scope.row.careLevel === '中' ? 'warning' : 'success'">
              {{ scope.row.careLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="200"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" @click="editBed(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleDeleteBed(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增/编辑床位对话框 -->
      <el-dialog :title="bedDialogTitle" :visible.sync="bedDialogVisible">
        <el-form :model="bedForm" label-width="120px">
          <el-form-item label="房间号">
            <el-input v-model="bedForm.roomNumber"></el-input>
          </el-form-item>
          <el-form-item label="床位号">
            <el-input v-model="bedForm.bedNumber"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="bedForm.status" placeholder="选择状态">
              <el-option label="空闲" value="空闲"></el-option>
              <el-option label="已入住" value="已入住"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入住老人">
            <el-input v-model="bedForm.elderlyName"></el-input>
          </el-form-item>
          <el-form-item label="入住日期">
            <el-date-picker v-model="bedForm.admissionDate" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="护理等级">
            <el-select v-model="bedForm.careLevel" placeholder="选择护理等级">
              <el-option label="低" value="低"></el-option>
              <el-option label="中" value="中"></el-option>
              <el-option label="高" value="高"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="bedForm.remarks"></el-input>
          </el-form-item>
          <el-form-item label="操作记录">
            <el-input v-model="bedForm.operationLog" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="bedDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleBedSubmit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增/编辑通知对话框 -->
      <el-dialog :title="notificationDialogTitle" :visible.sync="notificationDialogVisible">
        <el-form :model="notificationForm" label-width="120px">
          <el-form-item label="通知内容">
            <el-input v-model="notificationForm.content"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="notificationDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleNotificationSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import AsideLayout from '@/layout/asideLayout.vue'
import * as echarts from 'echarts'  // 引入 echarts
import axios from 'axios'

export default {
  name: 'BedOverview',
  components: {
    AsideLayout
  },
  data() {
    return {
      bedList: [],
      notifications: [],
      bedDialogVisible: false,
      bedDialogTitle: '',
      bedForm: {
        id: null,
        roomNumber: '',
        bedNumber: '',
        status: '',
        elderlyName: '',
        admissionDate: '',
        careLevel: '',
        remarks: '',
        operationLog: ''
      },
      notificationDialogVisible: false,
      notificationDialogTitle: '',
      notificationForm: {
        id: null,
        content: ''
      }
    }
  },
  computed: {
    occupiedBeds() {
      return this.bedList.filter(bed => bed.status === '已入住').length
    },
    availableBeds() {
      return this.bedList.filter(bed => bed.status === '空闲').length
    }
  },
  mounted() {
    this.fetchBedList()
    this.fetchNotifications()
    this.initCharts()  // 初始化图表
    this.updateBedChartData() // 更新床位分布图数据
  },
  methods: {
    fetchBedList() {
      axios.get('http://localhost:3000/api/beds')
        .then(response => {
          this.bedList = response.data
        })
        .catch(error => {
          console.error('Error fetching bed list:', error)
        })
    },
    fetchNotifications() {
      axios.get('http://localhost:3000/api/notifications')
        .then(response => {
          this.notifications = response.data
        })
        .catch(error => {
          console.error('Error fetching notifications:', error)
        })
    },
    refreshData() {
      this.fetchBedList()
      this.fetchNotifications()
      this.$message.success('数据已刷新')
    },
    viewDetails(row) {
      this.$message.success(`查看详情功能待实现，房间号：${row.roomNumber}`)
    },
    editBed(row) {
      this.bedDialogTitle = '编辑床位'
      this.bedForm = { ...row }
      this.bedDialogVisible = true
    },
    viewOperationLog(row) {
      this.$message.success(`查看操作记录功能待实现，房间号：${row.roomNumber}`)
    },
    initCharts() {
      const bedChartContainer = this.$refs.bedChart
      const bedChartInstance = echarts.init(bedChartContainer)
      const bedChartOption = {
        title: {
          text: '床位分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: 'bottom'
        },
        series: [
          {
            name: '床位状态',
            type: 'pie',
            radius: '50%',
            data: [
              { value: this.occupiedBeds, name: '已入住' },
              { value: this.availableBeds, name: '空闲' }
            ]
          }
        ]
      }
      bedChartInstance.setOption(bedChartOption)

      const usageChartContainer = this.$refs.usageChart
      const usageChartInstance = echarts.init(usageChartContainer)
      const usageChartOption = {
        title: {
          text: '床位使用率',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [80, 85, 90, 75, 70, 95],
            type: 'line'
          }
        ]
      }
      usageChartInstance.setOption(usageChartOption)
    },
    handleAddBed() {
      this.bedDialogTitle = '新增床位'
      this.bedForm = {
        id: null,
        roomNumber: '',
        bedNumber: '',
        status: '',
        elderlyName: '',
        admissionDate: '',
        careLevel: '',
        remarks: '',
        operationLog: ''
      }
      this.bedDialogVisible = true
    },
    handleBedSubmit() {
      if (this.bedForm.id) {
        axios.put(`http://localhost:3000/api/beds/${this.bedForm.id}`, this.bedForm)
          .then(() => {
            this.fetchBedList()
            this.bedDialogVisible = false
            this.$message.success('更新床位成功')
          })
          .catch(error => {
            console.error('Error updating bed:', error)
            this.$message.error('更新床位失败')
          })
      } else {
        axios.post('http://localhost:3000/api/beds', this.bedForm)
          .then(() => {
            this.fetchBedList()
            this.bedDialogVisible = false
            this.$message.success('新增床位成功')
          })
          .catch(error => {
            console.error('Error adding bed:', error)
            this.$message.error('新增床位失败')
          })
      }
    },
    handleAddNotification() {
      this.notificationDialogTitle = '新增通知'
      this.notificationForm = {
        id: null,
        content: ''
      }
      this.notificationDialogVisible = true
    },
    handleEditNotification(notification) {
      this.notificationDialogTitle = '编辑通知'
      this.notificationForm = { ...notification }
      this.notificationDialogVisible = true
    },
    handleNotificationSubmit() {
      if (this.notificationForm.id) {
        axios.put(`http://localhost:3000/api/notifications/${this.notificationForm.id}`, this.notificationForm)
          .then(() => {
            this.fetchNotifications()
            this.notificationDialogVisible = false
            this.$message.success('更新通知成功')
          })
          .catch(error => {
            console.error('Error updating notification:', error)
            this.$message.error('更新通知失败')
          })
      } else {
        axios.post('http://localhost:3000/api/notifications', this.notificationForm)
          .then(() => {
            this.fetchNotifications()
            this.notificationDialogVisible = false
            this.$message.success('新增通知成功')
          })
          .catch(error => {
            console.error('Error adding notification:', error)
            this.$message.error('新增通知失败')
          })
      }
    },
    handleDeleteNotification(notification) {
      this.$confirm(`确认删除通知 ${notification.content} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/notifications/${notification.id}`)
          .then(() => {
            this.fetchNotifications()
            this.$message.success('删除成功')
          })
          .catch(error => {
            console.error('Error deleting notification:', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    updateBedChartData() {
      const bedCounts = this.bedList.reduce((acc, bed) => {
        acc[bed.status] = (acc[bed.status] || 0) + 1;
        return acc;
      }, {});

      const totalBeds = this.bedList.length;
      const chartData = Object.entries(bedCounts).map(([key, value]) => ({
        name: key,
        value: totalBeds ? (value / totalBeds) * 100 : 0
      }));

      const bedChartOption = {
        title: {
          text: '床位分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: 'bottom'
        },
        series: [
          {
            name: '床位状态',
            type: 'pie',
            radius: '50%',
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      const bedChartContainer = this.$refs.bedChart;
      const bedChartInstance = echarts.init(bedChartContainer);
      bedChartInstance.setOption(bedChartOption);
    },
    updateOccupiedChartData() {
      const usageCounts = this.bedList.reduce((acc, bed) => {
        const admissionMonth = new Date(bed.admissionDate).getMonth() + 1; // 获取入住月份
        if (!acc[admissionMonth]) {
          acc[admissionMonth] = 0;
        }
        if (bed.status === '已入住') {
          acc[admissionMonth] += 1; // 计数已入住床位
        }
        return acc;
      }, {});

      const months = Object.keys(usageCounts);
      const occupiedData = months.map(month => usageCounts[month] || 0);

      const occupiedChartOption = {
        title: {
          text: '已入住床位',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: months.map(month => `${month}月`)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '已入住',
            type: 'line',
            data: occupiedData
          }
        ]
      };

      const occupiedChartContainer = this.$refs.occupiedChart;
      const occupiedChartInstance = echarts.init(occupiedChartContainer);
      occupiedChartInstance.setOption(occupiedChartOption);
    },

    updateAvailableChartData() {
      const usageCounts = this.bedList.reduce((acc, bed) => {
        const admissionMonth = new Date(bed.admissionDate).getMonth() + 1; // ���取入住月份
        if (!acc[admissionMonth]) {
          acc[admissionMonth] = 0;
        }
        if (bed.status === '空闲') {
          acc[admissionMonth] += 1; // 计数空闲床位
        }
        return acc;
      }, {});

      const months = Object.keys(usageCounts);
      const availableData = months.map(month => usageCounts[month] || 0);

      const availableChartOption = {
        title: {
          text: '空闲床位',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: months.map(month => `${month}月`)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '空闲',
            type: 'line',
            data: availableData
          }
        ]
      };

      const availableChartContainer = this.$refs.availableChart;
      const availableChartInstance = echarts.init(availableChartContainer);
      availableChartInstance.setOption(availableChartOption);
    },
    handleDeleteBed(bed) {
      this.$confirm(`确认删除床位 ${bed.bedNumber} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/beds/${bed.id}`)
          .then(() => {
            this.fetchBedList()
            this.$message.success('删除成功')
          })
          .catch(error => {
            console.error('Error deleting bed:', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  },
  watch: {
    bedList: {
      handler() {
        this.updateBedChartData();
        this.updateOccupiedChartData(); // 更新已入住图表数据
        this.updateAvailableChartData(); // 更新空闲图表数据
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.el-container {
  height: 100vh; /* 使容器高度适应视口 */
}

.el-main {
  padding: 20px;
  overflow-y: auto; /* 允许垂直滚动 */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-table {
  border-radius: 5px;
  overflow: hidden;
  width: 100%; /* 确保表格宽度适应容器 */
}

.statistics {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 5px;
}

.stat-icon {
  font-size: 24px;
  color: #409EFF;
  margin-right: 10px;
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.notification-list {
  list-style: none;
  padding: 0;
}

.notification-list li {
  padding: 5px 0;
  border-bottom: 1px solid #ebeef5;
}

.todo-list {
  list-style: none;
  padding: 0;
}

.todo-list li {
  padding: 5px 0;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}
</style>